import { Component, createApp } from 'vue'
import { addClass, removeClass } from '@/assets/js/dom'
const relativeCls = 'g-relative'

export default function createLoadingLikeDirective (Comp: Component) {
  let key: string
  return {
        mounted (el: any, binding: any) {
            // 则创建一个新的app实例，并挂载到el元素身上
            const instance = createApp(Comp).mount(document.createElement('div')) as any
            key = Comp.name || ((Comp as any).__hmrId)
            if (!el[key]) {
                el[key] = {}
            }
            el[key].instance = instance
            // 调用组件中的方法，设置组件的title值
            if (binding.arg) {
                instance.setTitle(binding.arg)
            }
            // 查看元素身上有没有这三个属性值
            if (!['fixed', 'relative', 'absolute'].includes(getComputedStyle(el).position)) {
                addClass(el, relativeCls)
            }
            // 当组件挂载时，判断loading值是否为true,为true则挂载到el上
            if (binding.value) {
                append(el)
            }
        },
        updated (el: any, binding: any) {
            if (binding.value !== binding.oldValue) { // 说明值改变了
                binding.value ? append(el) : remove(el)
            }
        }
    }

    function append (el: any) {
        el.appendChild(el[key].instance.$el)
    }

    function remove (el: any) {
        removeClass(el, relativeCls)
        el.removeChild(el[key].instance.$el)
    }
}
